source("./commons/setupNotebook.R")
# Factor the dataframes to get cleaner setup of column dimensions
df.submissions <- df.submissions %>% factor.data.frame()

#save.plot.png <- TRUE
save.plot.png <- FALSE
plot_output_dir <- "output/plots/00_Energy"
if (!dir.exists("output/plots/00_Energy")) {
  dir.create("output/plots/00_Energy")
}

if(FALSE) { # list available variables, similar to submission_overview
  reportedVariables <- df.submissions %>%
    select(model, variable, unit) %>%
    unique() %>% 
    mutate(exists = 1) %>%  # Create a column for presence
    pivot_wider(names_from = model, values_from = exists, values_fill = 0)
  View(reportedVariables)
  # write.csv(reportedVariables,"reportedVariables.csv", row.names = FALSE)
}
selectedLowScens <- c(
  "SSP2 - Low Emissions",
  "SSP2 - Very Low after High Overshoot",
  "SSP2 - Very Low with Limited Overshoot",
  "SSP1 - Very Low with Limited Overshoot",
  NULL
)
selectedLowScens <- factor(selectedLowScens, levels = selectedLowScens)

scen.linePlots <- selectedLowScens
scenarios.energyAreaPlots <- selectedLowScens
scen.energyBarPlots <- filterScenarios
period.linePlots <- c(seq(2020, 2050, 5))
period.energyAreaPlots <- seq(2020, 2100, 5)
year.energyBarPlots <- 2060

Lineplots

lp_vars <- c(
  "Primary Energy|Gas",
  "Primary Energy|Coal",
  "Primary Energy|Oil",
  "Secondary Energy|Electricity|Gas",
  "Secondary Energy|Electricity|Oil",
  "Secondary Energy|Electricity|Coal",
  "Electrification", # computed in setupNotebook.R
  NULL
)

for (v in lp_vars) {
  p <- plotLinesOneScenario(
    plot.var = v,
    plot.scen = scen.linePlots,
    plot.region = "World",
    plot.period = period.linePlots,
    submissions = df.submissions,
    historical = df.historical, 
    model.colors = plot.model.colors
  )
  
  p <- p + guides(color = guide_legend(nrow = 3))
  print(p)
  #if (save.plot.png) {
  #  ggsave(paste0(plot_output_dir, "/lineplot_", gsub("[^a-zA-Z0-9]", "", v), ".png"), p)
  #}
}

Lineplots with AR6 Data

lp_vars <- c(
  "Emissions|CO2",
  "Primary Energy|Gas"
)

for(v in lp_vars) {

  p <- plotLinesOneScenario(
    plot.var = v,
    plot.scen = scen.linePlots,
    plot.region = "World",
    submissions = df.submissions,
    historical = filter(df.ar6, model %in% IMPs.AR6$identifier),
    model.colors = plot.model.colors
  )
  print(p)
}

Marked Lineplots with combined models

# To change the figure size depending on the number of facets, adapt the header of this chunk.

mlp_vars <- c(
  "Secondary Energy|Electricity|Solar",
  "Secondary Energy|Electricity|Wind",
  "Secondary Energy|Electricity|Nuclear",
  "Secondary Energy|Electricity|Hydro",
  "CCS Estimate",
  NULL
)



df.plot_CCS <- df.submissions %>%  
  calc_addVariable("`CCS Estimate`" = "(`Primary Energy|Biomass|w/ CCS` * 0.1 + `Primary Energy|Coal|w/ CCS` * 0.1 +   `Primary Energy|Gas|w/ CCS`* 0.06) * 0.9 ", units = "GtCO2/yr", only.new = F) %>%
  filter(variable %in% mlp_vars) 

plot.hist <- df.historical %>% filter(variable %in% mlp_vars, model == "Ember") 

for (v in mlp_vars) {
  plotMarkedLinesNearTerm2(
    plot.var = v,
    historical = plot.hist,
    plot.period = period.linePlots,
    plot.scen = c(SSP3, SSP5, SSP2, SSP1),
    plot.region = "World",
    line.colors = plot.model.colors,
    line.types = plot.SSP.linetype,
    submissions = df.plot_CCS,
    separate.models = FALSE
  ) %>% print()
}

Marked Lineplots with separate models

# To change the figure size depending on the number of facets, adapt the header of this chunk.
mlp_vars <- c(
  "Emissions|CO2|Energy and Industrial Processes" ,
  "Emissions|CO2",
  "Emissions|CO2|AFOLU",
  "Price|Carbon",
  "Final Energy",
  "Final Energy|Electricity",
  "Primary Energy|Coal",
    "Primary Energy|Gas",
      "Primary Energy|Oil",
  "CCS Estimate",
  NULL
)



df.historical <-df.historical %>% factor.data.frame() 

for (v in mlp_vars) {
  plotMarkedLinesNearTerm(
    plot.var = v,
    plot.scen = c(SSP1, SSP2, SSP3, SSP5),
    plot.region = "World",
    plot.period = period.linePlots,
    submissions = df.plot_CCS,
    line.colors = brewer.pal(6, "Dark2"),
    line.types = plot.SSP.linetype,
    historical = df.historical %>% filter(model != "BP"), 
    separate.models = TRUE    
  ) %>% print()
} 
## NULL
## NULL
## NULL
## NULL
## NULL
## NULL
## NULL
## NULL
## NULL

Regional carbon prices per model

mlp_vars <- c(
  "Price|Carbon",
  NULL
)
mlp.emi.scens <- c(
  "Low Emissions",
  "Very Low with Limited Overshoot",
  NULL
)

for (v in mlp.emi.scens) {
  print(paste("Carbon price in", v, "scenarios"))
  plotMarkedLinesRegional(
    plot.var = "Price|Carbon",
    plot.scen = v,
    plot.region = c(RegionsTen, "World"),
    plot.period = period.linePlots,
    submissions = df.submissions,
    line.colors = c(brewer.pal(11, "Paired"), "#000000"),
    line.types = plot.SSP.linetype,
    historical = df.historical, 
    separate.models = TRUE    
  ) %>% print() 
} 
## [1] "Carbon price in Low Emissions scenarios"

## [1] "Carbon price in Very Low with Limited Overshoot scenarios"

Primary Energy

total <- "Primary Energy"
pe_data <- tribble(
  ~variable,                        ~label,        ~color,
  "Primary Energy|Other",           "Other",       "grey",
  "Primary Energy|Solar",           "Solar",       "#ffcc00",
  "Primary Energy|Wind",            "Wind",        "#337fff",
  "Primary Energy|Geothermal",      "Geothermal",  "#e51900",
  "Primary Energy|Hydro",           "Hydro",       "#191999",
  "Primary Energy|Ocean",           "Ocean",       "blue", 
  "Primary Energy|Nuclear",         "Nuclear",     "#ff33ff",
  "Primary Energy|Biomass|w/ CCS",  "Bio-CCS",     colorspace::lighten("#338833", 0.5),
  "Primary Energy|Biomass|w/o CCS", "Biomass",     "#338833",
  "Primary Energy|Gas|w/ CCS",      "Gas-CCS",     colorspace::lighten("#999959", 0.5),
  "Primary Energy|Gas|w/o CCS",     "Gas",         "#999959",
  "Primary Energy|Oil",             "Oil",         "#663a00",
  "Primary Energy|Coal|w/ CCS",     "Coal-CCS",    colorspace::lighten("#0c0c0c", 0.5),
  "Primary Energy|Coal|w/o CCS",    "Coal",        "#0c0c0c"
)
#  "Primary Energy|Biomass" = "Biomass",
#  "Primary Energy|Gas" = "Gas",
#  "Primary Energy|Coal" = "Coal",

pe.colors <- setNames(pe_data$color, pe_data$label)
pe.labels <- setNames(pe_data$label, pe_data$variable)
pe.vars <- names(pe.labels)

plotArea(
  submissions = df.submissions,
  plot.scen = scenarios.energyAreaPlots,
  plot.period = period.energyAreaPlots,
  plot.vars = pe.vars,
  plot.var.labels = pe.labels,
  plot.colors = pe.colors,
  y_label = "Primary Energy\n(EJ/yr)",
  total = total,
  interpolate = T,
  total.size = 1.1
)

plotStackedBarModScen(
  submissions = df.submissions,
  plot.scen = scen.energyBarPlots,
  plot.region = "World",
  plot.vars = pe.vars,
  plot.var.labels = pe.labels,
  plot.colors = pe.colors,
  plot.period = c(year.energyBarPlots),
  y_label = paste0(total, " in ", year.energyBarPlots, "\n(EJ/yr)"),
  total = total,
  bar.alpha = 0.8,
  layout.axis.x.angle = 30
)

Electricity production

total <- "Secondary Energy|Electricity"
se_data <- tribble(
  ~variable,         ~label,           ~color,
  "Other",           "Other",          "#ccc",
  "Hydrogen",        "Hydrogen",       "#aff",
  "Solar",           "Solar",          "#fc0",
  "Waste",           "Waste",          "#2aa",
  "Wind|Offshore",   "Wind offsh",     "#24f",
  "Wind|Onshore",    "Wind onsh",      "#48f",
  "Ocean",           "Ocean",          "#006",
  "Geothermal",      "Geothermal",     "#e20",
  "Hydro",           "Hydro",          "#229",
  "Nuclear",         "Nuclear",        "#f3f",
  "Biomass",         "Biomass",        "#060",
  "Gas",             "Gas",            "#774",
  "Oil",             "Oil",            "#630",
  "Coal",            "Coal",           "#111"
)
#"Trade|Secondary Energy|Electricity|Volume" = "Import",

se.colors <- setNames(se_data$color, se_data$label)
se.labels <- setNames(se_data$label, se_data$variable)
names(se.labels) <- paste0("Secondary Energy|Electricity|", names(se.labels))
se.vars <- names(se.labels)

plotArea(
  submissions = df.submissions,
  plot.scen = scenarios.energyAreaPlots,
  plot.period = period.energyAreaPlots,
  plot.vars = se.vars,
  plot.var.labels = se.labels,
  plot.colors = se.colors,
  y_label = "Electricity\n(EJ/yr)",
  total = total,
  interpolate = T,
  total.size = 1.1
)
## The following `from` values were not present in `x`: Secondary Energy|Electricity|Waste, Secondary Energy|Electricity|Ocean

plotStackedBarModScen(
  submissions = df.submissions,
  plot.scen =   scen.energyBarPlots,
  plot.region = "World",
  plot.vars = se.vars,
  plot.var.labels = se.labels,
  plot.colors = se.colors,
  plot.period = c(year.energyBarPlots),
  y_label = paste0(total, " in ", year.energyBarPlots, "\n(EJ/yr)"),
  total = total,
  bar.alpha = 0.8,
  layout.axis.x.angle = 30
)
## The following `from` values were not present in `x`: Secondary Energy|Electricity|Waste, Secondary Energy|Electricity|Ocean

### Battery-electric vehicles

vehicle_data <- tribble(
  ~variable,                        ~label,        ~color,
  "Fuel-Cell-Electric",             "Fuel-cell",   "#aaffff",
  "Battery-Electric",               "Battery",     "#ffcc00",
  "Plug-in Hybrid",                 "Hybrid",      "#ee22ee",
  "Internal Combustion",            "Combustion",  "#663a00",
)

for(metric in c("Sales", "Stocks")) {
  data_LDV <- vehicle_data %>% mutate(
    variable = paste0(metric, "|Transportation|Light-Duty Vehicle|",variable),
    label = paste("LDV", label))
  data_truck <- vehicle_data %>% mutate(
    variable = paste0(metric, "|Transportation|Truck|",variable),
    label = paste("Truck", label),
    color = colorspace::darken(color, 0.2))
  data_both <- bind_rows(data_truck, data_LDV)
  unit <- unique(filter(df.submissions, variable %in% data_both$variable)$unit)
  
  vehicle.colors <- setNames(data_both$color, data_both$label)
  vehicle.labels <- setNames(data_both$label, data_both$variable)

  plotArea(
    submissions = df.submissions,
    plot.scen = defScens,
    plot.period = period.energyAreaPlots,
    plot.vars = data_both$variable,
    plot.var.labels = vehicle.labels,
    plot.colors = vehicle.colors,
    y_label = paste0(metric, " (", unit, ")"),
    #total = "Primary Energy",
    interpolate = T,
    total.size = 1.1
  ) %>% print()
}
## The following `from` values were not present in `x`: Sales|Transportation|Truck|Plug-in Hybrid
## Warning: Removed 1875 rows containing non-finite outside the scale range (`stat_align()`).

## The following `from` values were not present in `x`: Stocks|Transportation|Truck|Plug-in Hybrid

Final Energy

FE carriers

vars <- c(
  "Final Energy",
  "Final Energy|Industry",
# "Final Energy|Non-Energy Use",
  "Final Energy|Residential and Commercial",
  "Final Energy|Transportation",
  "Final Energy|Bunkers",
  NULL
)

fe_subtypes <- tribble(
  ~variable,           ~label,             ~color,
  "Other",             "Other"      ,      "#ccc",
  "Electricity",       "Electricity",      "#fc6",
  "Hydrogen",          "Hydrogen",         "#aff",
  "Heat",              "Heat",             "#e88",
  "Solids|Biomass",    "Solid Biomass",    "#6b6",
  "Gases",             "All gases",        "#774",
  "Liquids",           "All liquids",      "#630",
  "Solids|Coal",       "Coal",             "#111",
#  "Solids|Coal",       "Coal Solids",      "#191919",
#  "Solids|Biomass",    "Biomass Solids",   "olivedrab",
#  "Liquids|Fossil",    "Fossil Liquids",   "gray40",
#  "Liquids|Efuel",     "Efuel Liquids",    "mediumpurple4",
#  "Gases|Efuel",       "Efuel Gases",      "plum2",
#  "Gases|Biomass",     "Biomass Gases",    "green",
#  "Gases|Fossil",      "Fossil Gases",     "gray90",
#  "Liquids|Biomass",   "Biomass Liquids",  "olivedrab3",
)

fe.sec.labels <- setNames(fe_subtypes$label, fe_subtypes$variable)
fe.sec.vars <- names(fe.sec.labels)
plot.vars.color <- setNames(fe_subtypes$color, fe_subtypes$label)

for (v in vars) {
  l <- fe.sec.labels
  names(l) <- paste0(v, "|", names(l))

  
  plotArea(
    submissions = df.submissions,
    plot.scen = scenarios.energyAreaPlots,
    plot.period = period.energyAreaPlots,
    plot.vars = paste0(v, "|", fe.sec.vars),
    plot.var.labels = l,
    plot.colors = plot.vars.color,
    y_label = paste0(v, "\n(EJ/yr)"),
    total = v,
    interpolate = T,
    total.size = 1.1
  ) %>% print()
  
  plotStackedBarModScen(
    submissions = df.submissions,
    plot.scen = scen.energyBarPlots,
    plot.region = "World",
    plot.vars = paste0(v, "|", fe.sec.vars),
    plot.var.labels = l,
    plot.colors = plot.vars.color,
    plot.period = c(year.energyBarPlots),
    y_label = paste0(v," in ",year.energyBarPlots,"\n(EJ/yr)"),
    total = v,
    bar.alpha = 0.8,
    layout.axis.x.angle = 30
  ) %>% print()
}
## The following `from` values were not present in `x`: Final Energy|Other

## The following `from` values were not present in `x`: Final Energy|Other

## The following `from` values were not present in `x`: Final Energy|Transportation|Heat

## The following `from` values were not present in `x`: Final Energy|Transportation|Heat

## The following `from` values were not present in `x`: Final Energy|Bunkers|Heat, Final Energy|Bunkers|Solids|Biomass, Final Energy|Bunkers|Solids|Coal
## Warning: Removed 20 rows containing non-finite outside the scale range (`stat_align()`).

## The following `from` values were not present in `x`: Final Energy|Bunkers|Heat, Final Energy|Bunkers|Solids|Biomass, Final Energy|Bunkers|Solids|Coal

FE carrier per sector

total <- "Final Energy"

if(T) { # with grouped Transportation (w/ bunkers)
  fe_data <- tribble( 
    ~variable,                                              ~label,                ~color,
    "Final Energy|Agriculture",                             "Agriculture",         "#5b5",
    "Final Energy|Industry|Other",                          "Industry Other",      "#666",
    "Final Energy|Residential and Commercial|Other",        "R&C Other",           "#888",
    "Final Energy|Transportation (w/ bunkers)|Other",       "Transportation Other","#444",
    "Final Energy|Industry|Electricity",                    "Industry Elec",       "#db5",
    "Final Energy|Residential and Commercial|Electricity",  "R&C Elec",            "#fc6",
    "Final Energy|Transportation (w/ bunkers)|Electricity", "Transport Elec",      "#b85",
    "Final Energy|Industry|Heat",                           "Industry Heat",       "#e88",
    "Final Energy|Residential and Commercial|Heat",         "R&C Heat",            "#faa",
    "Final Energy|Industry|Hydrogen",                       "Industry H2",         "#8dd",
    "Final Energy|Residential and Commercial|Hydrogen",     "R&C H2",              "#aff",
    "Final Energy|Transportation (w/ bunkers)|Hydrogen",    "Transport H2",        "#6bb",
    "Final Energy|Industry|Solids",                         "Industry Solids",     "#522",
    "Final Energy|Residential and Commercial|Solids",       "R&C Solids",          "#855",
    "Final Energy|Industry|Liquids",                        "Industry Liquids",    "#99d",
    "Final Energy|Residential and Commercial|Liquids",      "R&C Liquids",         "#66a",
    "Final Energy|Transportation (w/ bunkers)|Liquids",     "Transport Liquids",   "#88b",
    "Final Energy|Industry|Gases",                          "Industry Gases",      "#a6a",
    "Final Energy|Residential and Commercial|Gases",        "R&C Gases",           "#d9d",
    "Final Energy|Transportation (w/ bunkers)|Gases",       "Transport Gases",     "#b8b",
    "Final Energy|Non-Energy Use",                          "Non-energy",          "#111",
    "Final Energy|Other Sector",                            "Other",               "#ccc",
  )
} else { # with separated Transportation and Bunkers
  fe_data <- tribble( 
    ~variable,                                              ~label,                ~color,
    "Final Energy|Other Sector",                            "Other",               "#ccc",
    "Final Energy|Agriculture",                             "Agriculture",         "#5b5",
    "Final Energy|Industry|Other",                          "Industry Other",      "#666",
    "Final Energy|Residential and Commercial|Other",        "R&C Other",           "#888",
    "Final Energy|Transportation|Other",                    "Transport Other",     "#444",
    "Final Energy|Bunkers|Other",                           "Bunkers Other",       "#333",
    "Final Energy|Industry|Electricity",                    "Industry Elec",       "#db5",
    "Final Energy|Residential and Commercial|Electricity",  "R&C Elec",            "#fc6",
    "Final Energy|Transportation|Electricity",              "Transport Elec",      "#b85",
    "Final Energy|Bunkers|Electricity",                     "Bunkers Elec",        "#974",
    "Final Energy|Industry|Heat",                           "Industry Heat",       "#e88",
    "Final Energy|Residential and Commercial|Heat",         "R&C Heat",            "#faa",
    "Final Energy|Industry|Hydrogen",                       "Industry H2",         "#8dd",
    "Final Energy|Residential and Commercial|Hydrogen",     "R&C H2",              "#aff",
    "Final Energy|Transportation|Hydrogen",                 "Transport H2",        "#6bb",
    "Final Energy|Bunkers|Hydrogen",                        "Bunkers H2",          "#599",
    "Final Energy|Industry|Solids",                         "Industry Solids",     "#522",
    "Final Energy|Residential and Commercial|Solids",       "R&C Solids",          "#855",
    "Final Energy|Industry|Liquids",                        "Industry Liquids",    "#99d",
    "Final Energy|Residential and Commercial|Liquids",      "R&C Liquids",         "#ccf",
    "Final Energy|Transportation|Liquids",                  "Transport Liquids",   "#88b",
    "Final Energy|Bunkers|Liquids",                         "Bunkers Liquids",     "#669",
    "Final Energy|Industry|Gases",                          "Industry Gases",      "#a6a",
    "Final Energy|Residential and Commercial|Gases",        "R&C Gases",           "#d9d",
    "Final Energy|Transportation|Gases",                    "Transport Gases",     "#b8b",
    "Final Energy|Bunkers|Gases",                           "Bunkers Gases",       "#979",
    "Final Energy|Non-Energy Use",                          "Non-energy",          "#111",
  )
}

plot.var.labels <- setNames(fe_data$label, fe_data$variable) 
plot.vars.color <- setNames(fe_data$color, fe_data$label)

plotArea(
  submissions = df.submissions,
  plot.scen = scenarios.energyAreaPlots,
  plot.period = period.energyAreaPlots,
  plot.vars = names(plot.var.labels),
  plot.var.labels = plot.var.labels,
  plot.colors = plot.vars.color,
  y_label = "Final Energy\n(EJ/yr)",
  total = total,
  interpolate = T,
  total.size = 1.1
) %>% print()
## Warning: Removed 300 rows containing non-finite outside the scale range (`stat_align()`).

plotStackedBarModScen(
  submissions = df.submissions,
  plot.scen = scen.energyBarPlots,
  plot.region = "World",
  plot.vars = names(plot.var.labels),
  plot.var.labels = plot.var.labels,
  plot.colors = plot.vars.color,
  plot.period = c(year.energyBarPlots),
  y_label = paste0(total, " in ", year.energyBarPlots, "\n(EJ/yr)"),
  total = total,
  bar.alpha = 0.8,
  layout.axis.x.angle = 30
) %>% print()

Emissions

Sectoral emissions

total <- "Emissions|CO2|Energy and Industrial Processes"
emi_data <- tribble(
  ~variable,                                                ~label,        ~color,
  "Emissions|CO2|Energy|Demand|Other Sector",               "Other demand","#ccc",
  "Emissions|CO2|Energy|Demand|Industry",                   "Industry",    "#f84",
  "Emissions|CO2|Energy|Demand|Residential and Commercial and AFOFI", "Build+AFOFI",   "#7c5",
  #"Emissions|CO2|Energy|Demand|AFOFI",                      "AFOFI",       "#5a5",
  #"Emissions|CO2|Energy|Demand|Residential and Commercial", "Buildings",   "#8f4",
  "Emissions|CO2|Energy|Demand|Transportation",             "Transport",   "#48f",
  "Emissions|CO2|Energy|Demand|Bunkers",                    "Bunkers",     "#25b",
  "Emissions|CO2|Energy|Supply",                            "Supply",      "#ff6",
  "Emissions|CO2|Industrial Processes",                     "Ind. Proc.",  "#e20"
)

emi.labels <- setNames(emi_data$label, emi_data$variable)
emi.colors <- setNames(emi_data$color, emi_data$label)

plotArea(
  submissions = df.submissions,
  plot.scen = scenarios.energyAreaPlots,
  plot.period = period.energyAreaPlots,
  plot.vars = emi_data$variable,
  plot.var.labels = emi.labels,
  plot.colors = emi.colors,
  y_label = "Emissions\n(MtCO2/yr)",
  total = total,
  interpolate = T,
  total.size = 1.1
)

plotStackedBarModScen(
  submissions = df.submissions,
  plot.scen = scen.energyBarPlots,
  plot.vars = emi_data$variable,
  plot.var.labels = emi.labels,
  plot.colors = emi.colors,
  plot.period = c(year.energyBarPlots),
  y_label = paste0("Emissions|CO2 in ", year.energyBarPlots, "\n(MtCO2/yr)"),
  total = total,
  bar.alpha = 0.8,
  layout.axis.x.angle = 30
)

Net emissions

total = "Emissions|CO2"
df.emissions.co2 <- df.submissions %>%
  filter(unit == "Mt CO2/yr") %>%
     calc_addVariable("`Emissions|CO2|Others`" =
                        "`Emissions|CO2|Other` +
                         `Emissions|CO2|Other Capture and Removal` + 
                         `Emissions|CO2|Product Use` + 
                         `Emissions|CO2|Waste`",
                      units = "Mt CO2/yr", only.new = F, completeMissing = TRUE) %>%
     calc_addVariable("`Emissions|CO2|Sum`" = 
                        "`Emissions|CO2|AFOLU` + 
                         `Emissions|CO2|Energy|Supply` + 
                         `Emissions|CO2|Energy|Demand` + 
                         `Emissions|CO2|Industrial Processes` + 
                         `Emissions|CO2|Others`", units = "Mt CO2/yr", only.new = F, completeMissing = TRUE)

emi_data <- tribble(
  ~variable,                            ~label,                 ~color,
  "Emissions|CO2|AFOLU",                "AFOLU",                "#8b8",
  "Emissions|CO2|Energy|Supply",        "Supply",               "#ff6",
  "Emissions|CO2|Energy|Demand",        "Demand",               "#6cc",
  "Emissions|CO2|Industrial Processes", "Industrial Processes", "#e20",
  "Emissions|CO2|Others",               "Others",               "#ccc",
)
emi.labels <- setNames(emi_data$label, emi_data$variable)
emi.colors <- setNames(emi_data$color, emi_data$label)

for (scen in selectedLowScens) {
  p <- plotAreaOneScenario(
    submissions = df.emissions.co2,
    plot.scen = scen,
    plot.period = period.energyAreaPlots,
    plot.vars = emi_data$variable,
    plot.var.labels = emi.labels,
    plot.colors = emi.colors,
    y_label = "CO2 Emissions\n(Mt CO2/yr)",
    total = total,
    total.label = "Total (reported)",
    sum = "Emissions|CO2|Sum",
    sum.label = "Sum (computed)",
    interpolate = T,
    total.size = 1.1,
  ) + ggtitle(scen)
  print(p)
}

plotStackedBarModScen(
  submissions = df.emissions.co2,
  plot.scen = selectedLowScens,
  plot.region = "World",
  plot.vars = names(emi.labels),
  plot.var.labels = emi.labels,
  plot.colors = emi.colors,
  plot.period = c(year.energyBarPlots),
  y_label = paste0("Emissions|CO2 in ", year.energyBarPlots, "\n(EJ/yr)"),
  total = total,
  bar.alpha = 0.8,
  layout.axis.x.angle = 30
) %>% print()

Gross Removal = Net Emissions - Gross Emissions

df.gross.emissions.co2 <- df.emissions.co2 %>%
   calc_addVariable("`Computed Removal|CO2|Energy|Supply`" =
      "`Emissions|CO2|Energy|Supply` - `Gross Emissions|CO2|Energy|Supply`",
      units = "Mt CO2/yr", only.new = F) %>% 
   calc_addVariable("`Computed Removal|CO2|Energy|Demand`" =
      "`Emissions|CO2|Energy|Demand` - `Gross Emissions|CO2|Energy|Demand`",
      units = "Mt CO2/yr", only.new = F) %>% 
   calc_addVariable("`Computed Removal|CO2|Industrial Processes`" =
      "`Emissions|CO2|Industrial Processes` - `Gross Emissions|CO2|Industrial Processes`",
      units = "Mt CO2/yr", only.new = F)

emi_data <- tribble(
  ~variable,                            ~label,                 ~color,
  "Emissions|CO2|AFOLU",                "AFOLU",                "#8b8",
  "Gross Emissions|CO2|Energy|Supply",  "Supply(+)",            "#ff6",
  "Gross Emissions|CO2|Energy|Demand",  "Demand(+)",            "#6cc",
  "Gross Emissions|CO2|Industrial Processes", "IP(+)",          "#e20",
  "Computed Removal|CO2|Energy|Supply", "Supply(-)",            "#dd5",
  "Computed Removal|CO2|Energy|Demand", "Demand(-)",            "#4aa",
  "Computed Removal|CO2|Industrial Processes", "IP(-)",         "#c00",
  "Emissions|CO2|Others",               "Others",               "#ccc",
)
emi.labels <- setNames(emi_data$label, emi_data$variable)
emi.colors <- setNames(emi_data$color, emi_data$label)

for (scen in selectedLowScens) {
p <- plotAreaOneScenario(
  submissions = df.gross.emissions.co2,
  plot.scen = scen,
  plot.region = "World",
  plot.models = c("AIM", "GCAM", "IMAGE", "REMIND-MAgPIE", "WITCH"),
  plot.vars = emi_data$variable,
  plot.period = seq(2020, 2100, 5),
  plot.var.labels = emi.labels,
  plot.colors = emi.colors,
  y_label = "CO2 Emissions\n(Mt CO2/yr)",
  total = "Emissions|CO2",
  total.label = "Total (reported)",
  sum = "Emissions|CO2|Sum",
  sum.label = "Sum (computed)",
  interpolate = T,
  total.size = 1.1,
) + ggtitle(scen) + geom_hline(yintercept = 0, color = "black", linewidth = 0.3)

print(p)
}

Carbon storage

total <- "Carbon Capture|Geological Storage"
ccs_data <- tribble(
  ~variable,                                                ~label,        ~color,
  "Carbon Capture|Geological Storage|Other Sources",        "Other",       "#ccc",
  "Carbon Capture|Geological Storage|Direct Air Capture",   "Atmospheric", "#aff",
  "Carbon Capture|Geological Storage|Synthetic Fuels",      "Synthetic",   "#66a",
  "Carbon Capture|Geological Storage|Biomass",              "Biomass",     "#6b6",
  "Carbon Capture|Geological Storage|Fossil",               "Fossil",      "#522",
  "Carbon Capture|Geological Storage|Industrial Processes", "Industrial",  "#2ba",
)

plot.var.labels <- setNames(ccs_data$label, ccs_data$variable)
plot.vars.color <- setNames(ccs_data$color, ccs_data$label)

# take the absolute value of storage values
df.plot <- df.submissions %>%
  filter(variable %in% c(ccs_data$variable, total)) %>%
  group_by(model, scenario, variable, region, period, value) %>%
  mutate(value = abs(value)) %>%
  ungroup()
  
p <- plotArea(
  submissions = df.plot,
  plot.scen = scenarios.energyAreaPlots,
  plot.period = period.energyAreaPlots,
  plot.vars = ccs_data$variable,
  plot.var.labels = plot.var.labels,
  plot.colors = plot.vars.color,
  y_label = "Geological storage\n(Mt CO2/yr)",
  total = total,
  interpolate = T,
  total.size = 1.1
) %>%
  print()

plotStackedBarModScen(
  submissions = df.plot,
  plot.scen = scen.energyBarPlots,
  plot.vars = names(plot.var.labels),
  plot.var.labels = plot.var.labels,
  plot.colors = plot.vars.color,
  plot.period = c(year.energyBarPlots),
  y_label = paste0(total, " in ", year.energyBarPlots, "\n(Mt CO2/yr)"),
  total = total,
  bar.alpha = 0.8,
  layout.axis.x.angle = 30
)

Per capita indicators

mlp_vars <- c(
  "Final Energy",
  "Final Energy|Industry",
  "Final Energy|Residential and Commercial",
  "Final Energy|Transportation",
  "Final Energy|Other Sector",
  "Production|Iron and Steel|Steel",
  "Production|Chemicals|High-Value Chemicals",
  "Production|Non-Metallic Minerals|Cement Clinker",
  "Energy Service|Transportation|Passenger|Road",
  "Energy Service|Residential|Floor Space",
  "Energy Service|Residential and Commercial|Floor Space",
  NULL
)

scen <- intersect(union(LowScens,M),union(SSP1,SSP2))

# compute GDP per capita
# for models missing GDP and Population, could use average of other models
df.plot <- df.submissions %>%
  filter(scenario %in% scen) %>%
  calc_addVariable(
    data.frame(
      variable = paste("`GDP pCap`", sep=""),
      formula = paste("(`GDP|PPP` / `Population` * 1000)", sep=""),
      unit = "$2010/yr/cap"
    ),
    only.new = F
  )

for (v in mlp_vars) {
  v_pCap <- paste(v, "pCap")
  v.unit <- unique(filter(df.plot, variable == v)$unit)
  
  # compute variable per capita
  df.loop <- df.plot %>%
    filter(variable %in% c(v, "Population", "GDP pCap")) %>%
    calc_addVariable(
      data.frame(
        variable = paste("`", v_pCap, "`", sep=""),
        formula = paste("(`", v, "` / `Population` * 1000)", sep=""),
        unit = paste0(v.unit, " / bn cap")
      ),
      only.new = F
    )

  plotLinesMultipleScenarios(
    plot.var = v_pCap,
    plot.scen = scen,
    plot.region = "World",
    submissions = df.loop,
    y.split = NULL
  ) %>% print()

  plotLinesXaxis(
    df = df.loop,
    var.x = "GDP pCap",
    var.y = v_pCap
  ) %>% print()

  plotMarkedLinesRegional(
    plot.var = v_pCap,
    plot.scen = c("Very Low with Limited Overshoot", "Medium Emissions"), #names(plot.emi.scen.letter),, 
    plot.region = c(RegionsTen, "World"),
    plot.period = period.linePlots,
    submissions = df.loop,
    line.colors = c(brewer.pal(11, "Paired"), "#000000"),
    line.types = plot.emi.scen.linetype, #c(1:100),
    #historical = df.historical, 
    separate.models = TRUE,
    linestyle.column = "emi.scen",
    linestyle.header = "Emission scenario"
  ) %>% print()
}